package com.ys.peony.ui.activity;

import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ys.peony.R;
import com.ys.peony.app.HttpURL;
import com.ys.peony.base.BaseActivity;
import com.ys.peony.http.JCHttpManagerUtils;
import com.ys.peony.http.base.BaseRespCallBack;
import com.ys.peony.interfaces.RadioGroupChangeListener;
import com.ys.peony.model.BusiTypeFileListResp;
import com.ys.peony.model.BusiTypeFileModel;
import com.ys.peony.model.JiekuanrenModel;
import com.ys.peony.ui.fragment.ClientPicFragment;
import com.ys.peony.utils.JSONUtil;
import com.ys.peony.utils.LoadingProgressUtils;
import com.ys.peony.utils.LogUtil;
import com.ys.peony.utils.NetUtils;
import com.ys.peony.utils.SharePreferencesUtils;
import com.ys.peony.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by yml on 17/5/29.
 */

public class BusiLoanInfoActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.id_viewpager)
    ViewPager mViewPager;
    @BindView(R.id.pic_rg)
    RadioGroup pic_rg;
    @BindView(R.id.top_left_btn)
    RadioButton top_left_btn;
    @BindView(R.id.top_right_btn)
    RadioButton top_right_btn;
    @BindView(R.id.back_btn)
    RelativeLayout backBtn;
    @BindView(R.id.submit_btn)
    TextView submitBtn;

    public final static int PAGE_CLIENT = 1;
    public final static int PAGE_VEHICLE = 2;
    private JiekuanrenModel loanModel;
    public List<Fragment> fragments = new ArrayList<Fragment>();
    private String fileType = "1";//1:借款人资料  2:补件资料  3:打回补件资料  4:免审资料

    @Override
    protected int getContentResId() {
        return R.layout.activity_busiloan_file;
    }

    @Override
    protected void initView() {
        backBtn.setOnClickListener(this);

        Bundle bd = getIntent().getExtras();
        if (bd != null) {
            loanModel = (JiekuanrenModel) bd.getSerializable("loanModel");
            fileType = bd.getString("fileType");
        }
        if ("1".equals(fileType) && !"0".equals(loanModel.getLoanStatus()) && !"5".equals(loanModel.getLoanStatus())
                && !"7".equals(loanModel.getLoanStatus())) {
            submitBtn.setEnabled(false);
            submitBtn.setTextColor(getResources().getColor(R.color.color_c0c0c0));
        } else {
            submitBtn.setEnabled(true);
            submitBtn.setTextColor(getResources().getColor(R.color.color_F96161));
        }

        if ("1".equals(fileType) && !isSubmitPermission()) {
            submitBtn.setEnabled(false);
            submitBtn.setTextColor(getResources().getColor(R.color.color_c0c0c0));
        }
        if ("4".equals(fileType)) {
            submitBtn.setEnabled(false);
            submitBtn.setTextColor(getResources().getColor(R.color.color_c0c0c0));
        }
        fragments.add(new ClientPicFragment(loanModel, fileType, PAGE_CLIENT));
        fragments.add(new ClientPicFragment(loanModel, fileType, PAGE_VEHICLE));
        submitBtn.setOnClickListener(this);
        initAdapter();
        if (!NetUtils.isNetworkConnected(this)) {
            ToastUtils.showToast(this, getResources().getString(R.string.no_net_error));
            return;
        }
        LoadingProgressUtils.showProgressDialog(this);
        getPicTypeList();
        getUploadedFiles();
    }

    /**
     * time:2017/12/15
     * 2017/12/15 判断当前业务人员是否有提交业务资料权限 tips: gps岗位在业务登记不具有提交业务资料权限
     *
     * @return true:有权限 false:没有权限
     */
    private boolean isSubmitPermission() {
        if (SharePreferencesUtils.getInstance().getUserModel().getPermissions().contains("busiLoanAction:create")) {
            return true;
        } else {
            return false;
        }
    }

    private void initAdapter() {
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        });

        pic_rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
                switch (i) {
                    case R.id.top_left_btn:
                        mViewPager.setCurrentItem(0);
                        break;
                    case R.id.top_right_btn:
                        mViewPager.setCurrentItem(1);
                        break;
                }
            }
        });

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                changeBtn(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void changeBtn(int position) {
        switch (position) {
            case 0:
                top_left_btn.setChecked(true);
                break;
            case 1:
                top_right_btn.setChecked(true);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.submit_btn:
                //提交
                submitLoanInfo();
                break;
        }
    }

    /**
     * 获取资料文件列表
     */
    private void getPicTypeList() {
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<>();
        params.put("userId", Long.parseLong(SharePreferencesUtils.getInstance().getUserModel().getId()));
        params.put("loanId", loanModel.getId());

        if ("3".equals(fileType)) {
            params.put("patchId", loanModel.getPatchId());
        }
        String httpUrl = HttpURL.riskInfoList;
        if ("2".equals(fileType)) {
            httpUrl = HttpURL.patchRiskInfoList;
        } else if ("3".equals(fileType)) {
            httpUrl = HttpURL.backPatchRiskInfoList;
        } else if ("4".equals(fileType)) {
            httpUrl = HttpURL.riskInfoListFree;
        }

        httpManager.get(httpUrl, params, new BaseRespCallBack(this) {

            public void onRespSuccess(String respStr) {
                BusiTypeFileListResp resp = JSONUtil.parseObject(respStr, BusiTypeFileListResp.class);
                if (resp != null) {
                    ((ClientPicFragment) fragments.get(0)).setTypeList(resp.getClient());
                    if (resp.getVechicle() != null && resp.getVechicle().size() > 0) {
                        ((ClientPicFragment) fragments.get(1)).setTypeList(resp.getVechicle().get(0).getRiskInfoList());
                    }
                }
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(msg);
            }
        });
    }

    /**
     * 描述：获取已上传图片列表
     */
    public void getUploadedFiles() {
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<>();

        params.put("userId", Long.parseLong(SharePreferencesUtils.getInstance().getUserModel().getId()));//(必传) Long  用户主键
        params.put("loanId", Long.parseLong(loanModel.getId()));//(必传) Long 业务主键

        if ("3".equals(fileType)) {
            params.put("patchId", Long.parseLong(loanModel.getPatchId()));
        }
        String httpUrl = HttpURL.busiLoanInfoList;
        if ("2".equals(fileType)) {
            httpUrl = HttpURL.patchBusiLoanInfoList;
        } else if ("3".equals(fileType)) {
            httpUrl = HttpURL.backPatchBusiLoanInfoList;
        }
        httpManager.get(httpUrl, params, new BaseRespCallBack() {

            public void onRespSuccess(String respStr) {
                final BusiTypeFileListResp resp = JSONUtil.parseObject(respStr, BusiTypeFileListResp.class);
                ((ClientPicFragment) fragments.get(0)).setUploadedFileList(resp.getClient());
                ((ClientPicFragment) fragments.get(1)).setUploadedFileList(resp.getVehicle());
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                if (!"2".equals(fileType)) {
                    ToastUtils.showToast(BusiLoanInfoActivity.this, msg);
                }
            }
        });
    }

    /**
     * 提交业务信息  补件 打回补件
     */
    private void submitLoanInfo() {
        //TODO 添加图片是否都已经上传的判断
        LoadingProgressUtils.showProgressDialog(this);
        JCHttpManagerUtils httpManager = new JCHttpManagerUtils();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", Long.parseLong(SharePreferencesUtils.getInstance().getUserModel().getId()));//(必传) Long  用户主键
        String httpUrl = HttpURL.ywdjSubmit;
        params.put("loanId", loanModel.getId());//(必传) Long 业务主键

        if ("2".equals(fileType)) {
            httpUrl = HttpURL.submitPatch;
        } else if ("3".equals(fileType)) {
            params.put("patchId", loanModel.getPatchId());//(必传) Long 补件主键
            params.put("taskId", loanModel.getTaskId());//(必传) String 任务主键
            params.put("processId", loanModel.getProcessId());//(必传) String 流程主键

            httpUrl = HttpURL.submitBackPatch;
        }
        httpManager.get(httpUrl, params, new BaseRespCallBack() {

            public void onRespSuccess(String respStr) {
                ToastUtils.showToast(BusiLoanInfoActivity.this, "提交成功");
                setResult(RESULT_OK);
            }

            @Override
            public void onRespFailure(String msg) {
                super.onRespFailure(msg);
                ToastUtils.showToast(BusiLoanInfoActivity.this, msg);
            }
        });
    }

/*    public void showPic(final BusiTypeFileModel busiTypeFileModel, final int position) {
        PicShowDialog dialog = new PicShowDialog(this, new CustomAlertDialogCallBack() {

            @Override
            public void onCancelBtnClicked() {
            }

            @Override
            public void onSureBtnClicked() {
                delPicFile(busiTypeFileModel, position);
            }

            @Override
            public void onSureBtnClicked1(String editStr) {
            }
        });
        dialog.setImgPath(busiTypeFileModel.getFiles().get(position).getFilePath());
    }*/

}
